//
//  LJFFMDBManager.m
//  SevenZhou
//
//  Created by qianfeng on 15/9/23.
//  Copyright (c) 2015年 ljf. All rights reserved.
//

#import "LJFFMDBManager.h"

@implementation LJFFMDBManager

+ (instancetype)shareInstance
{
    static LJFFMDBManager *manager = nil;
    
    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken, ^
                  {
                      manager = [[LJFFMDBManager alloc] init];
                  });
    return manager;
}

- (instancetype)init
{
    self = [super init];
    if (self)
    {
        NSString *filePath = [NSHomeDirectory() stringByAppendingString:@"/Documents/sevenZhou.db"];
        
        NSLog(@"filePath==%@",filePath);
        
        
        self.dataBase = [FMDatabase databaseWithPath:filePath];
        
        if (![self.dataBase open])
        {
            NSLog(@"数据库打开失败");
        }
    }
    return self;
}

-(void)creatTableOfDataBaseWithTableName:(NSString *)tableName dictionary:(NSDictionary *)dict
{
    NSMutableArray *arr = [[NSMutableArray alloc] init];
    
    for (NSString *key in dict)
    {
        NSString *str = [NSString stringWithFormat:@"%@ %@",key,dict[key]];
        [arr addObject:str];
    }
    
    NSString *dictString = [arr componentsJoinedByString:@","];
    
    NSString *keyString = [NSString stringWithFormat:@"create table if not exists %@(id integer primary key autoincrement,%@)",tableName,dictString];
    
    if (![self.dataBase executeUpdate:keyString])
    {
        NSLog(@"创建表失败");
    }
}

-(void)deleteTableDataOfDBWithName:(NSString *)name
{
    NSString *keyString = [NSString stringWithFormat:@"delete from %@",name];
    
    if(![self.dataBase executeUpdate:keyString])
    {
        NSLog(@"删除失败");
    }
}

-(void)deleteTableDataOfDBWithName:(NSString *)name andkeyString:(NSString *)key
{
    NSString *keyString = nil;
    
    if (key)
    {
        keyString = [NSString stringWithFormat:@"delete from %@ %@",name,key];
    }
    else
    {
        keyString = [NSString stringWithFormat:@"delete from %@",name];
    }
    
    if(![self.dataBase executeUpdate:keyString])
    {
        NSLog(@"删除失败");
    }
}

-(FMResultSet *)selectFromTableName:(NSString *)name
{
    NSString *keyString = [NSString stringWithFormat:@"select * from %@",name];
    
    return [self.dataBase executeQuery:keyString];
}

-(FMResultSet *)selectFromTableName:(NSString *)name andkeystring:(NSString *)key
{
    NSString *keyString = nil;
    
    if (key)
    {
        keyString = [NSString stringWithFormat:@"select * from %@ %@",name,key];
    }
    else
    {
        keyString = [NSString stringWithFormat:@"select * from %@",name];
    }
    
    return [self.dataBase executeQuery:keyString];
}


@end
